﻿#ifndef PST_MAINWINDOW_H
#define PST_MAINWINDOW_H

#include <QMainWindow>
#include <QMap>
#include "QToolButton.h"
#include "PostEnumType.h"
#include "parser/JsonDef.h"
#include "BaseWidget/idamainwindow.h"
#include "InfomationGraph3DBasical.h"
#include "MainWindowSignalHandler.h"
#include "DialogDataImportConfiguration.h"
QT_BEGIN_NAMESPACE
namespace Ui
{
    class MainWindow;
    class DialogImportProjectFirst;
    class DialogImportProjectSecond;
}; // namespace Ui

class QLabel;
class QComboBox;
class QTabWidget;
class QTreeView;
class QStandardItem;
QT_END_NAMESPACE

class ElaContentDialog;
class vtkStructuredGrid;
class IdaDialogFrame;

namespace pst
{
    class TextFileParser;
    class CenterWidget;
    class SelectDatatDialog;
    class IWidgetSignal;
    class MutiVTKFilesReader;
    class NearFieldDataGenerator;
    class ThreeDSurfacePlotSelectorDialog;
    class FarFieldDataGenerator;
    class MutiVTUFilesReader;
    class Curve2DPlotor;
    class Graph2DWindowBase;
    class VTPFilesReader;
    class JsonParser;
    class PostLineEdit;
    class PostComboBox;

    struct FileInfo
    {
        QString m_filePath;
        QString m_fileName;
        FileDataTypes m_fileType;
    };

    extern QString g_outputDir;

    class MainWindow : public IdaMainWindow
    {
        Q_OBJECT

    public:
        MainWindow(QWidget* parent = nullptr);
        ~MainWindow();

        inline void setIsNotInput(bool isNotInput) { m_isNotInput = isNotInput; }
        inline bool getIsNotInput() { return m_isNotInput; }

        inline void setInputDirList(const QList<QString>& dir) { m_inputDirList = dir; }
        inline QList<QString> getInputDirList() const { return m_inputDirList; }
        inline void setOutputDir(const QString& dir)
        {
            m_outputDir = dir;
            g_outputDir = dir;
        }
        inline QString getOutputDir() const { return m_outputDir; }

        void setToolButtonDynamicTypeText(const QString& text);
        QString getToolButtonDynamicTypeText() const;

        QString getClipperNormalDirection() const;
        double getClipperOriginDistance() const;

        void setToolButtonFastBackState(bool state);
        void setToolButtonFastForwardState(bool state);

        void setToolButtonExportMotionGraphState(bool state);
        void updateAnimationButtonState();

        TextFileParser* getTextFileParserByProjectTreeItem(int projectTreeItemID);
        TextFileParser* getTextFileParserByDataSourceByOpenProject(QString dataSources);

        InfomationGraph3DBasical* BuildCompleteGraph3DInfoByProjectTreeItemThreeDCloudMap(int projectTreeItemID);
        InfomationGraph3DBasical* BuildCompleteGraph3DInfoByProjectTreeItemThreeDSurfacePlot(int projectTreeItemID);
        InfomationGraph3DBasical* BuildCompleteGraph3DInfoByProjectTreeItemSurfaceElectricFieldMap(int projectTreeItemID);
        InfomationGraph3DBasical* BuildCompleteGraph3DInfoByProjectTreeItemTableChart(int projectTreeItemID);

        QList<QPair<QStandardItem*, QString>> GetAttachmentPointDatas(QStandardItem* currentGraphItem);

        //检测是否可用使用剖面
        int getCurrent3DWindowGraphSize();

        bool TextImportDataProcessing(int itemID, QString filePath, const QVector<std::tuple<QString, DialogDataImportConfiguration::DataProperty, QVector<double>>>& datas, const JsonParser::ProjectDataPointer& projectData);

        void slot_toolButtonThunderstormZoneClicked();

        void slot_setToolButtonExportMotionGraph2InterfaceState(bool state);

        inline QMultiHash<int, QStandardItem*> getEvaluationSubmissionNodeCorrespondenceData() const { return m_EvaluationSubmissionNodeCorrespondence; };
        inline QMap<QStandardItem*, QString> getPointElectricFieldData() const { return m_pointElectricFieldData; };

    private slots:
        void slot_clearCurrentProjectAllData();
        void slot_updateWidgetCursor(Qt::CursorShape shap);
        void slot_resetWidgetCursor();
        bool slot_toolBtnImportDataClick(QString filepath);
        void slot_exportBtnClick(); // 数据导出槽函数
        void slot_importProjectData();
        bool slot_importProjectDataInternal(bool fromTheCommand = false);
        void slot_OpenProjectFile(QString filePath);
        void slot_saveProjectData(QString filePath);
        bool slot_readTxtData(const QString& filePath, QStandardItem* item, const QStringList& geometryFileName = QStringList(), const ResultDataPointer& resultDataPointer = ResultDataPointer());
        bool slot_readVTUData(const QString& filepath, QStandardItem* item, const QStringList& geometryFileName = QStringList());
        bool slot_readVTKData(const QString& filePath, QStandardItem* item, const QStringList& geometryFileName = QStringList());
        bool slot_readVTPData(const QString& filePath, QStandardItem* item, const QStringList& geometryFileName = QStringList());
        void slot_checkGraphType(const QList<QStandardItem*>& index);
        void slot_displayNew2DGraph(bool isOpenNewWindow = true);
        // 展示图像的时候，先完成数据类型转换，然后再展示
        void slot_displayNewSurfaceElectricFieldGraph(bool isOpenNewWindow = true);
        void slot_sentChosenArrayInfo(InfomationGraph3DBasical* info, bool isOpenNewWindow);
        void slot_displayNewThreeDCloudMap(bool openNewWindow = true);
        void slot_displayNewThreeDSurfacePlot(bool isOpenNewWindow = true);
        void slot_displayInTableWidget();
        void slot_pasteFile(QStandardItem* copyFileItem, QStandardItem* pasteFileItem);
        void slot_saveGraphToLocal();
        // 选完数据后，开始打开图画线
        void slot_sendSelectedInfo(int& variableIndex,
                                   QList<QPair<int, QList<int>>>& chosenData, QList<int>& valueIndexs, bool* isSuccess, QList<int> selectParserIndexs = QList<int>(), bool isOpenNewWindow = true);
        void solt_set2DPlotType(int type);
        void slot_receiveThreeDSurfacePlotData(int graphType, int variableIndex, int frequencyIndex, int readerIndex, QString filePath, QString name, QString geometryFileName, bool isOpenNewWindow);
        void slot_receiveThreeDCloudMapData(bool useNewWindow, int graphType, int variableIndex, int readerIndex, QString filePath, QString name, QString geometryFileName, int resultDataIndex);
        void slot_receiveSurfaceElectricFieldGraphData(int graphType, int currentIndex, int readerIndex, QString sReaderType, QString sFilePath, QString sName, QString geometryFileName, bool isOpenNewWindow);
        void slot_receiveTableData(int readerIndex);

        void slot_sendQuestionMessageToUI(int& result, const QString& title, const QString& message);
        void slot_sendErrorMessageToUI(const QString& message);
        void slot_addToCurrentGraph(const QList<QStandardItem*>& index);
        void slot_sendChosen3DSurfaceData(InfomationGraph3DBasical* info, int freIndex, int valueGroupIndex, bool isOpenNewWindow);
        void slot_sendChosen3DCloudData(InfomationGraph3DBasical* info, bool isOpenNewWindow);

        void slot_ActionHomePage();
        void slot_ActionDataAnalysis();
        void slot_ActionDisplay();

        void slot_toolButtonSelfAdaptationClicked();
        void slot_toolButtonIsometricViewClicked();
        void slot_toolButtonTopViewClicked();
        void slot_toolButtonUpwardViewClicked();
        void slot_toolButtonFrontViewClicked();
        void slot_toolButtonRearViewClicked();
        void slot_toolButtonLeftViewClicked();
        void slot_toolButtonRightViewClicked();

        bool slot_toolButtonModelDisplay();

        void slot_saveScript();
        void slot_editScript();
        void slot_operationScript();

        void slot_toolButtonTranslationClicked(bool checked);
        void slot_toolButtonRotationClicked(bool checked);
        // void slot_toolButtonModelDisplay(bool checked);
        void slot_toolButtonPlayStateChanged(bool checked);
        void slot_toolButtonActiveClipperStateChanged(bool checked);

        void slot_SubtractSliderPushButtonClicked(); // 单位滑动条减按钮点击
        void slot_AddSliderPushButtonClicked();      // 单位滑动条加按钮点击
        void slot_SliderPressed();                   // 单位滑动条按下
        void slot_SliderReleased();                  // 单位滑动条释放
        void slot_SliderValueChanged(int value);     // 单位滑动条值改变

        // 调用生成报告相关
        void slot_openReportModel();
        void slot_screenshootToReport();

        QPixmap captureScreenShot();

        // 当前选中tab页改变时，更新状态栏提示信息
        void slot_tabBarCurrentChanged();

        void slot_getTwoDResultDataPointer(const TextFileParser* textFIleParser, ResultDataPointer& resultDataPointer);
        void slot_getTwoDDataSources(const TextFileParser* textFIleParser, QString& sourcesStr);
        void slot_getThreeDDataSources(const void* reader, QString& sourcesStr);
        void slot_measureButtonStateChanged(int state);
        void slot_standardCcurveButtonSctateChanged(bool state);

        void slot_setEnableAnimationBtn(bool enable);
        void slot_updateAnimationButtonState();
        void slot_updateThunderstormZoneButtonState();
        void slot_setShowAnimationTextWidget(bool bShow);
        void slot_setToolBarAnimationDataInfo(const QString& type,
                                              const QString& unit, double currentValue, int totalNumber, int currentIndex);

        void slot_showImportProjectFirst(Ui::DialogImportProjectFirst* uiFirst, IdaDialogFrame* dialog, const QDir& targetDir);
        void slot_selectedAttachmentPointPathIndex(int index);

        void slot_saveGifSuccess(bool isSuccess);

        void slot_setDisplayModelButtonCheckState(bool checked);

        void slot_setClipperButtonCheckState(bool checked);
        // 表格数据
        void slot_hideOrShowTableColumn(int windowId, QString selectedIndex);
        void slot_changeTbColumnName(int windowId, int index, QString newName);
        void slot_flushTbBySelectedRow(int windowId, QString parms);
        void slot_exportTbData(int windowId, QString filePath, QString delimiter, int onlyVisible);
        void slot_highlightSelectedTbColumns(int windowId, QString parms);

        // 工程数据
        void slot_doPrjFileWrite(QString fileName);
        void slot_doPrjFileRead(QString fileName);

        void slot_doPrjCloseTree(int index);
        void slot_doPrjTreeCopyDir(int index);
        void slot_doPrjTreePasteDir(int srcId, int destId);
        void slot_doPrjTreeCopyData(int index);
        void slot_doPrjTreePasteData(int srcId, int destId);
        void slot_doPrjTreeExpandDir(int index);
        void slot_doPrjTreeCollapseDir(int index);
        void slot_closeCenterTableBar(int index);
        void slot_changeCurrentTabBar(int index);

        void slot_submitEvaluation(int windowId, int evaluationType, QString parms);

        //模型显示
        void slot_modelDisplaySettingData(int windowUniversalID, bool toolButtonActiveClipperIsChecked, bool toolButtonModelDisplayIsChecked, bool hasAnyGeometrySuccess);
        void slot_ActiveClipperSettingData(int windowUniversalID, bool toolButtonActiveClipperIsChecked, bool toolButtonModelDisplayIsChecked, bool hasAnyGeometrySuccess, QString direction, double clipperValue);

    private:
        void initWindow();
        void initMainToolBar();
        void initHomePageToolBar();
        void initDataAnalysisToolBar();
        void initDisplayToolBar();
        void initStatusBar();
        /// @brief 初始化中心视图，左侧工程树及右侧的结果查看视图
        void initContentWidget();
        void checkFileType(const QList<FileDataTypes>& inputType, bool& is2D, bool& isPolar, bool& is3D,
                           bool& isTwoDHeatMap, bool& isThreeDCloudMap, bool& isThreeDSurfacePlot, bool& TwoDPeakValleyGraph, bool& isDataTable);
        void ShowSelecetDataDialog(bool isOpenNewWindow = true); // 显示数据选择窗口

        void initConnections();

        void exportPolarGraphDatas(QVector<QPair<QString, QVector<double>>>& datas,
                                   Graph2DWindowBase* window, const QVector<double>& keyData);
        void exportCommonGraphDatas(QVector<QPair<QString, QVector<double>>>& datas,
                                    Graph2DWindowBase* window, const QVector<double>& keyData);
        void exportHeatMapDatas(QVector<QPair<QString, QVector<double>>>& datas,
                                Graph2DWindowBase* window, const QVector<double>& keyData);

        void ReadStandardExampleData();
        friend void MainWindowSignalHandler::slot_toolButtonFormatViewClicked();
        friend void MainWindowSignalHandler::slot_comboBoxStandardSelectionCurrentIndexChanged(int index);

        void ReadHIRFExtrapolation();
        friend void MainWindowSignalHandler::slot_toolButtonHirfExtrapolationClicked();
        friend bool MainWindowSignalHandler::slot_computeHIRF(const QString& graphNames, double incidentWaveFieldValue, 
            const QString& HIRFName, const QString& typeName, bool isCheckBoxChecked);

        // 调用生成报告相关
        void InitChildReportProcess();

        /// @brief 当前窗口类型识别
        /// @return 当前窗口类型
        CurrentWindowType currentWindowTypeRecognize(bool& isShouldEnableAnimation);

        // 根据窗口，更新clipper的UI状态
        void updateCipperUI();

        /// @brief 更新状态栏信息
        /// @param text 消息
        /// @param isbegin 是否开始
        /// @param isEnd 是否结束
        void UpdateStatusBarInformation(QString text, bool isbegin);

        void RecycleAllReader();
        void RecycleReaderByItems(const QList<QStandardItem*>& itemList);

        void exportPstData(QString fileDestPath);

        void writeImportedTextToProjectTempIO(vtkTable* table, const QString fileName);

        /// @brief 保存点电场数据文件到tempIO，用于评估提交
        /// @param projectTreeChildItem  项目树点电场子节点
        /// @return 是否成功
        bool savePointElectricFieldData(QStandardItem* projectTreeChildItem);
    private:
        Ui::MainWindow* ui;
        // 调用生成报告相关
        QProcess* m_process = Q_NULLPTR;
        QProcess* m_report = Q_NULLPTR;
        QWidget* m_widget = Q_NULLPTR;
        QStatusBar* m_statusBar{nullptr};
        QProgressBar* m_pLeftToRightProBar{nullptr};
        QToolButton* m_actionHomePage{nullptr};
        QToolButton* m_actionDataAnalysis{nullptr};
        QToolButton* m_actionDisplay{nullptr};

        MainWindowSignalHandler* m_menuSignalHandlerInstance;
        /// @brief 软件关闭弹窗
        ElaContentDialog* _closeDialog{nullptr};
        /// @brief 中心视图
        CenterWidget* m_centerWidget{nullptr};

        // QHash<QString, QString > m_fileType; //记录文件类型，用于检测可用于显示哪些图
        QHash<QStandardItem*, ResultDataPointer> m_fileType; // 记录文件类型，用于检测可用于显示哪些图
        TextFileParser* m_textFileParser;

        // 主页按钮
        QToolButton* m_toolButton2DGraph{nullptr};                 // 二维折线图
        QToolButton* m_toolButtonPolarGraph{nullptr};              // 极坐标图
        QToolButton* m_toolButtonTwoDHeatMap{nullptr};             // 二维热力图
        QToolButton* m_toolButton3DCloudMap{nullptr};              // 三维云图
        QToolButton* m_toolButton3DSurfacePlot{nullptr};           // 三维曲面图
        QToolButton* m_toolButtonSurfaceElectricFieldMap{nullptr}; // 三维电场图
        QToolButton* m_toolButtonTable{nullptr};                   // 表格数据
        QToolButton* m_toolButtonFormatView{nullptr};              // 标准显示
        QLabel* m_labelStandardSelection{nullptr};                 // 标准选择
        QComboBox* m_comboBoxStandardSelection{nullptr};           // 标准选择
        QLabel* m_labelDataSelection{nullptr};                     // 数据选择
        QComboBox* m_comboBoxDataSelection{nullptr};               // 数据选择
        QToolButton* m_toolButtonScreenshotToReport{nullptr};      // 截图至报告
        QToolButton* m_toolButtonSaveImageToLocal{nullptr};        // 保存图片

        // 数据分析按钮
        QToolButton* m_toolButtonTotalQuantityCalculation{nullptr}; // 总量计算
        QToolButton* m_toolButtonHirfExtrapolation{nullptr};        // HIRF外推
        QToolButton* m_toolButtonWaveformAnalysis{ nullptr };        // 波形分析
        // QToolButton* m_toolButtonLightningZoning{ nullptr };         // 雷电分区
        QToolButton* m_toolButtonShieldingEfficiency{nullptr};   // 屏蔽效能
        QToolButton* m_toolButtonThunderstormZone{ nullptr };     // 雷电分区
        QToolButton* m_toolButtonTransferFunction{nullptr};       // 传递函数
        QToolButton* m_toolButtonIPLCalculation{nullptr};        // IPL计算
        QToolButton* m_toolButtonCurveSmoothing{nullptr};        // 曲线平滑
        QToolButton* m_toolButtonInterpolation{nullptr};         // 插值
        QAction* m_linearInterpolation{nullptr};                 // 线性插值
        QAction* m_logarithmicInterpolationSingleAxisX{nullptr}; // 单X轴对数插值
        QAction* m_logarithmicInterpolationSingleAxisY{nullptr}; // 单Y轴对数插值
        QAction* m_logarithmicInterpolationDoubleAxis{nullptr};  // 双对数轴对数插值
        QAction* m_splineInterpolation{nullptr};                 // 样条插值
        QAction* m_polynomialInterpolation{nullptr};             // 多项式插值

        QToolButton* m_toolButtonMeasure{nullptr};              // 测量
        QToolButton* m_toolButtonEvaluationSubmission{nullptr}; // 评估提交
        QAction* m_actionHalfPowerBeamWidth{nullptr};           // 半波功率波束宽度
        QAction* m_standingWaveBandwidth{nullptr};              // 驻波宽度
        QAction* m_MaxValue{nullptr};                           // 最大值
        QAction* m_MinValue{nullptr};                           // 最小值
        QAction* m_AverageValue{nullptr};                       // 平均值

        // 显示按钮
        QToolButton* m_toolButtonSelfAdaptation{nullptr}; // 自适应
        QToolButton* m_toolButtonAmplify{nullptr};        // 放大
        QToolButton* m_toolButtonMinification{nullptr};   // 缩小
        QToolButton* m_toolButtonTranslation{nullptr};    // 平移
        QToolButton* m_toolButtonRotation{nullptr};       // 旋转
        QToolButton* m_toolButtonIsometricView{nullptr};  // 等距视图
        QToolButton* m_toolButtonTopView{nullptr};        // 俯视图
        QToolButton* m_toolButtonUpwardView{nullptr};     // 仰视图
        QToolButton* m_toolButtonFrontView{nullptr};      // 正视图
        QToolButton* m_toolButtonRearView{nullptr};       // 后视图
        QToolButton* m_toolButtonLeftView{nullptr};       // 左视图
        QToolButton* m_toolButtonRightView{nullptr};      // 右视图
        QToolButton* m_toolButtonModelDisplay{nullptr};   // 模型
        QToolButton* m_toolButtonActiveClipper{nullptr};  // 剖面
        QLabel* m_labelNormal{nullptr};                   // 法向
        QLabel* m_labelLocation{nullptr};                 // 位置
        QLabel* m_labelLocationUnit{nullptr};             // 位置单位
        PostComboBox* m_comboBoxClipperNormal{nullptr};      // 法向
        PostLineEdit* m_lineEditClipperOrigin{nullptr};      // 位置
        QToolButton* m_toolButtonFastBack{nullptr};       // 快退
        QToolButton* m_toolButtonPlay{nullptr};           // 播放
        QToolButton* m_toolButtonFastForward{nullptr};    // 快进
        QWidget* m_animationInfoBarWidgetLeft{nullptr};   // 动画信息
        QWidget* m_animationInfoBarWidgetRight{nullptr};  // 动画信息

        QLabel* m_labelAniamtionInfoType{nullptr};        // 类型
        QLabel* m_labelAniamtionInfoTypeValue{nullptr};   // 类型输入框
        QLabel* m_labelAniamtionInfoValue{nullptr};       // 数值
        QLabel* m_labelAniamtionInfoValueValue{nullptr};  // 数值输入框
        QLabel* m_labelAniamtionInfoUnit{nullptr};        // 单位
        QLabel* m_labelAniamtionInfoUnitValue{nullptr};   // 单位输入框
        QPushButton* m_SubtractSliderPushButton{nullptr}; // 位置滑动条减按钮
        QSlider* m_sliderAniamtionInfoPosition{nullptr};  // 位置滑动条
        QPushButton* m_AdditionSliderPushButton{nullptr}; // 位置滑动条加按钮

        QToolButton* m_toolButtonDynamicType{nullptr};       // 类型：相机
        QAction* m_actionCamera{nullptr};                    // 类型：相机
        QAction* m_actionData{nullptr};                      // 类型：相机
        QToolButton* m_toolButtonDynamicSetting{nullptr};    // 动态设置
        QToolButton* m_toolButtonExportMotionGraph{nullptr}; // 导出动图

        bool m_toolButtonTranslationState{false};
        bool m_toolButtonRotationState{false};

        QList<QStandardItem*> m_currentChosenFiles;

        QList<QString> m_inputDirList{QDir::homePath()};
        QString m_outputDir{QDir::homePath()};
        int m_screenShotNum{0};

        SelectDatatDialog* m_selecetDataDialog; // 点击曲线类型后开始选数据，选完数据再画图
        QList<QString> m_optionalKeyList;
        QList<QString> m_errorMessageList;
        QList<TextFileParser*> m_selectFileList;
        QHash<QStandardItem*, TextFileParser*> m_txtReader{};     // 包括.txt等
        QHash<QStandardItem*, MutiVTUFilesReader*> m_vtuReader{}; // （包括.vtu、.pvtu、.pvtp等
        QHash<QStandardItem*, MutiVTKFilesReader*> m_vtkReader{}; // 包括vtkPolyData/vtkUnstructedGrid类型
        QHash<QStandardItem*, vtkSmartPointer<VTPFilesReader>> m_vtpReader{};
        QList<FarFieldDataGenerator*> m_farFieldDataGeneratorList;
        IWidgetSignal* m_signalInstance;
        //bool m_openNewWindow{true};
        FileDataType m_2DPlotType{FileDataType::File2DCurve};
        // QList<vtkSmartPointer<vtkStructuredGrid>> m_addedFarFieldData;

        // FarFieldDataGenerator* m_farFieldGenerator;

        QList<ResultDataPointer> m_pyFileTypeList;
        QList<TextFileParser*> m_pyTextParserList;
        QList<MutiVTUFilesReader*> m_pyVtuReaderList;
        QList<MutiVTKFilesReader*> m_pyVtkReaderList;
        QList<vtkSmartPointer<VTPFilesReader>> m_pyVtpReaderList;
        QString m_lastSelectPath;

        QList<TextFileParser*> m_standardExampleData;
        QList<QPair<QString, QList<QString>>> m_fileValueData; // 标准文件对应的value数据
        QList<TextFileParser*> m_HIRFExtrapolation;

        bool m_sliderAniamtionIsPressed{false};
        bool m_isNotInput{false};

        /// @brief 评估提交节点对应关系
        ///<int, QStandardItem*> int为所属大类sim_scene，QStandardItem*为子节点
        QMultiHash<int, QStandardItem*> m_EvaluationSubmissionNodeCorrespondence{};

        /// @brief 评估提交功能，点电场数据处理结果
        ///<QStandardItem*, QString> QStandardItem*为点电场对应的项目树子节点，QString为数据文件保存完整路径
        QMap<QStandardItem*, QString> m_pointElectricFieldData;
    };
} // namespace pst

#endif // PST_MAINWINDOW1_H
